package cn.ms.doctor.ExceptionHandler;

import cn.ms.doctor.Utils.GlobalMessage;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestControllerAdvice
@Log4j2
public class BaseExceptionHandler{

    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {RuntimeException.class})
    public Object handleException(Exception e,HttpServletResponse response ) {
        log.error(e.getLocalizedMessage());
        log.error(e.getMessage());
        return new GlobalMessage(response.getStatus()==200?500:response.getStatus(),3,"出现异常了哦，请联系管理员处理~",null);
    }

    /**
     * 处理404绕过Controller问题
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public GlobalMessage handleNotFound(NoHandlerFoundException e) {
        return  new GlobalMessage(404,3,e.getMessage(),null);
    }
}
